<template>
  <el-container>
    <el-header>
      <el-input
        v-model="queryInfo.noticeContent"
        @blur="getNoticeInfo"
        placeholder="搜索学习资源"
        prefix-icon="el-icon-search"
      ></el-input>

      <el-button
        type="primary"
        style="margin-left: 5px"
        icon="el-icon-plus"
         v-if="us=='admin'"
        @click="showPublishNoticeDialog"
        >发布新学习资源
      </el-button>
    </el-header>

    <el-main>
      <!--操作的下拉框-->
      <el-select
        @change="selectChange"
        clearable
        v-if="selectedInTable.length !== 0"
        v-model="selected"
        :placeholder="'已选择' + selectedInTable.length + '项'"
        style="margin-bottom: 25px"
      >
        <el-option v-for="(item, index) in optionInfo" :key="index" :value="item.desc">
          <span style="float: left">{{ item.label }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{
            item.desc
          }}</span>
        </el-option>
      </el-select>

      <el-table
        ref="multipleTable"
        highlight-current-row
        v-loading="loading"
        :border="true"
        :data="noticeInfo"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column align="center" type="selection" width="55"> </el-table-column>

        <el-table-column label="资源名称" width="600px;">
          <template slot-scope="scope">
            <p v-html="scope.row.name"></p>
          </template>
        </el-table-column>

        <el-table-column align="center" prop="createTime" label="发布时间">
        </el-table-column>

        <!-- <el-table-column align="center" label="更新时间">
          <template slot-scope="scope">
            {{ scope.row.updateTime === null ? "暂无更新" : scope.row.updateTime }}
          </template>
        </el-table-column> -->

        <!-- <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <p v-if="scope.row.status === 1" style="color: limegreen">当前系统学习资源</p>
            <p v-if="scope.row.status === 0" style="color: #ffd550">历史学习资源</p>
          </template>
        </el-table-column> -->

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="warning" @click="showUpdateNoticeDialog(scope.row)"
              >查看学习资源</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <el-pagination
        style="margin-top: 25px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNo"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-main>

    <el-dialog
      title="发布学习资源"
      :visible.sync="publishTableVisible"
      width="70%"
      @close="resetPublishForm"
      center
    >
      <el-form :model="publishForm" :rules="publishFormRules" ref="publishForm">
        <el-form-item label="名称" label-width="120px" prop="name">
          <el-input placeholder="请输入资源名称" v-model="publishForm.name" style="margin-left: 5px;width:100%" 
                    :rows="2"></el-input>
        </el-form-item>
        <el-form-item label="图片" label-width="120px" prop="image">
            <el-upload
              :action="uploadImageUrl + '/teacher/uploadQuestionImage'"
              :on-preview="uploadPreview"
              :on-remove="handleRemove"
              :headers="headers"
              :before-upload="beforeAvatarUpload"
              :file-list="fileList"
              list-type="picture"
              :on-success="uploadImgSuccess"
              name="file">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10M</div>
            </el-upload>
          </el-form-item>
        <el-form-item label="资源文件" label-width="120px" prop="image">
            <el-upload
              :action="uploadImageUrl + '/teacher/uploadQuestionImage'"
              :on-preview="uploadPreview"
              :on-remove="handleRemove2"
              :headers="headers"
              :before-upload="beforeAvatarUpload2"
              :file-list="fileList2" 
              :on-success="uploadImgSuccess2"
              name="file">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">不超过10M</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="内容" label-width="120px" prop="content">
            <el-input v-model="publishForm.content" style="margin-left: 5px" type="textarea"
                      :rows="2"></el-input>
          </el-form-item>
        <!-- <el-form-item label="学习资源内容" label-width="120px" prop="content">
          <div id="publishEditor"></div>
        </el-form-item> -->

        <!-- <el-form-item label="当前最新学习资源?" label-width="120px" prop="status">
          <el-select v-model="publishForm.status" placeholder="是否设置为当前最新学习资源">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item> -->
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="publishTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="publishNotice">发 布</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="查看学习资源"
      :visible.sync="updateTableVisible"
      width="70%"
      @close="$refs['updateForm'].resetFields()"
      center
    >
      <el-form :model="updateForm" :rules="updateFormRules" ref="updateForm">
        <block v-if="us=='admin'"> 
          <el-form-item label="名称" label-width="120px" prop="name">
            <el-input placeholder="请输入资源名称" v-model="updateForm.name" style="margin-left: 5px;width:100%" 
                      :rows="2"></el-input>
          </el-form-item>
        <el-form-item label="图片" label-width="120px" prop="image">
            <el-upload
              :action="uploadImageUrl + '/teacher/uploadQuestionImage'"
              :on-preview="uploadPreview"
              :on-remove="handleRemove"
              :headers="headers"
              :before-upload="beforeAvatarUpload"
              list-type="picture"
              :on-success="uploadImgSuccess"
              name="file">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10M</div>
            </el-upload>
            <el-image :src="updateForm.poto" style="width:150px"></el-image>
          </el-form-item>
          <el-form-item label="内容" label-width="120px" prop="content">
            <el-input v-model="publishForm.content" style="margin-left: 5px" type="textarea"
                      :rows="2"></el-input>
          </el-form-item>
          <el-form-item label="学习资源内容" label-width="120px" prop="content"> 
              <el-input v-model="updateForm.content" style="margin-left: 5px" type="textarea"
                        :rows="2"></el-input>
          </el-form-item>
        </block>
        <block v-else>
        <el-form-item label="学习资源内容" label-width="120px" >
          <div v-html="updateForm.content"></div>
        </el-form-item>

        </block>

        <!-- <el-form-item label="当前最新学习资源?" label-width="120px" prop="status">
          <el-select
            v-model="updateForm.status"
            :disabled="currentUpdateNoticeStatus === '1'"
            placeholder="是否设置为当前最新学习资源"
          >
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
          <span v-show="currentUpdateNoticeStatus === '1'" style="color: red">
            请将其他学习资源设置为当前使用学习资源后再操作正在使用的学习资源
          </span>
        </el-form-item> -->
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="updateTableVisible = false">关 闭</el-button>
        <el-button type="primary" v-if="us=='admin'" @click="updateNotice">更 新</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
// 导入富文本编辑器
import E from "wangeditor";
import notice from "@/api/notice";
import utils from "@/utils/utils";
import { generateSign } from '@/utils/sign'

export default {
  name: "NoticeManage",
  data() {
    return {
      uploadImageUrl: process.env.VUE_APP_UPLOAD_IMAGE_URL,
      //查询学习资源的参数
      queryInfo: {
        noticeContent: "",
        pageNo: 1,
        pageSize: 10,
      },
      //下拉选择框的数据
      optionInfo: [
        {
          label: "删除",
          desc: "delete",
        },
      ],
      fileList:[],
      fileList2:[],
      //下拉框所选择的数据
      selected: "",
      // 所有学习资源信息
      noticeInfo: [],
      // 表格数据预加载
      loading: true,
      // 学习资源总数
      total: 0,
      // 被选中的表格行
      selectedInTable: [],
      // 发布学习资源对话框
      publishTableVisible: false,
      // 发布的表单
      publishForm: {
        content: "",
        status: "1",
        title: "",
        title: "kc",
        poto: "",
        name: "",
      },
      publishFormRules: {
        content: [
          {
            required: true,
            message: "请输入学习资源内容",
            trigger: "blur",
          },
        ],
      },
      // 发布学习资源的富文本编辑器
      publishEditor: null,
      // 更新学习资源的富文本编辑器
      updateEditor: null,
      // 更新学习资源的对话框是否展示
      updateTableVisible: false,
      // 更新的表单
      updateForm: {
        nid: "",
        content: "",
        status: "",
      },
      updateFormRules: {
        content: [
          {
            required: true,
            message: "请输入学习资源内容",
            trigger: "blur",
          },
        ],
      },
      us:'',
      // 当前更新的学习资源的信息
      currentUpdateNoticeStatus: "",
    };
  },
  created() {
    this.us = localStorage.getItem("username");
    this.getNoticeInfo();
  },
  methods: { 
    uploadPreview (file) {
      window.location.href = file.url;
      // this.backShowImgUrl = file.response.data
      // this.backShowImgVisible = true
    }, 
    handleRemove (file, fileList) {
      this.publishForm.poto = '';
      // this.addQuForm.images.map((item, index) => {//移除图片在表单中的数据
      //   if (item === file.response.data) this.addQuForm.images.splice(index, 1)
      // })
    }, 
    //新增题目中的上传图片的格式大小限制
    beforeAvatarUpload (file) {
      const isImg = file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg'
      const isLt = file.size / 1024 / 1024 < 10

      if (!isImg) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }

      if (!isLt) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }
      return isImg && isLt
    },
    //新增题目中的上传图片成功后的钩子函数
    uploadImgSuccess (response, file, fileList) {
      // this.addQuForm.images.push(response.data)
      this.publishForm.poto = response.data;
    }, 
    handleRemove2 (file, fileList) {
      this.publishForm.title = '';
    }, 
    //新增题目中的上传图片的格式大小限制
    beforeAvatarUpload2 (file) {
      // const isImg = file.type === 'video/mp4' 
      // const isLt = file.size / 1024 / 1024 < 10
      // debugger;
      // if (!isImg) {
      //   this.$message.error('上传只能是 mp4/MP4 格式!')
      // }

      // if (!isLt) {
      //   this.$message.error('上传大小不能超过 10MB!')
      // }
      // return isImg && isLt
    },
    //新增题目中的上传图片成功后的钩子函数
    uploadImgSuccess2 (response, file, fileList) {
      // this.addQuForm.images.push(response.data)
      this.publishForm.title = response.data;
    }, 
    //获取用户信息
    getNoticeInfo() {
      notice.getAllNotice(this.queryInfo).then((resp) => {
        if (resp.code === 200) {
          this.noticeInfo = resp.data.data;
          this.total = resp.data.total;
          this.loading = false;
        } else {
          this.$notify({
            title: "Tips",
            message: "获取信息失败",
            type: "error",
            duration: 2000,
          });
        }
      });
    },
    //表格某一行被选中
    handleSelectionChange(val) {
      this.selectedInTable = val;
    },
    //分页插件的大小改变
    handleSizeChange(val) {
      this.queryInfo.pageSize = val;
      this.getNoticeInfo();
    },
    //分页插件的页数
    handleCurrentChange(val) {
      this.queryInfo.pageNo = val;
      this.getNoticeInfo();
    },
    //功能下拉框被选择
    selectChange(val) {
      //清空上一次的操作
      this.selected = "";
      //表格中所选中的学习资源的id
      let ids = [];
      this.selectedInTable.map((item) => {
        if (item.status !== 1) {
          // **防止删除当前使用学习资源
          ids.push(item.nid);
        }
      });
      if (val === "delete") {
        //删除
        if (ids.length === 0) {
          this.$message.error("不允许删除当前使用学习资源");
        } else {
          notice.deleteNotice({ ids: ids.join(",") }).then((resp) => {
            if (resp.code === 200) {
              //删除成功后,回调更新数据
              this.getNoticeInfo();
              this.$notify({
                title: "Tips",
                message: resp.message,
                type: "success",
                duration: 2000,
              });
            } else {
              this.$notify({
                title: "Tips",
                message: "操作失败",
                type: "error",
                duration: 2000,
              });
            }
          });
        }
      }
    },
    // 显示发布新闻对话框
    showPublishNoticeDialog() {
      this.fileList = [];
      this.fileList2 = [];
      this.publishForm={};
      this.publishTableVisible = true;
      window.setTimeout(() => {
        this.createPublishWangEditor();
      }, 200);
    },
    // 发布学习资源的表单信息重置
    resetPublishForm() {
      //清空表格数据
      this.$refs["publishForm"].resetFields();
    },
    // 创建新增新闻的富文本编辑器
    createPublishWangEditor() {
      if (!this.publishEditor) {
        this.publishEditor = new E("#publishEditor");
        this.publishEditor.create();
      }
      // 设置编辑区域高度为 300px
      this.publishEditor.config.height = 300;
      this.publishEditor.config.onchange = (html) => {
        this.publishForm.content = html;
      };
      this.publishEditor.txt.html(this.publishForm.content);
    },
    // 创建更新新闻的富文本编辑器
    createUpdateWangEditor() {
      if (!this.updateEditor) {
        this.updateEditor = new E("#updateEditor");
        this.updateEditor.create();
      }
      // 设置编辑区域高度为 300px
      this.updateEditor.config.height = 300;
      this.updateEditor.config.onchange = (html) => {
        this.updateForm.content = html;
      };
      this.updateEditor.txt.html(this.updateForm.content);
    },
    // 发布学习资源
    publishNotice() {
      utils.validFormAndInvoke(
        this.$refs["publishForm"],
        () => {
          if(this.publishForm.nid){ 
            notice.updateNotice(this.publishForm).then((resp) => {
              if (resp.code === 200) {
                this.getNoticeInfo();
                this.$notify({
                  title: "Tips",
                  message: resp.message,
                  type: "success",
                  duration: 2000,
                });
              } else {
                this.$notify({
                  title: "Tips",
                  message: resp.message,
                  type: "error",
                  duration: 2000,
                });
              }
              this.publishTableVisible = false;
            });
          }else{ 
          notice.publishNotice(this.publishForm).then((resp) => {
            if (resp.code === 200) {
              this.getNoticeInfo();
              this.$notify({
                title: "Tips",
                message: resp.message,
                type: "success",
                duration: 2000,
              });
            } else {
              this.$notify({
                title: "Tips",
                message: resp.message,
                type: "error",
                duration: 2000,
              });
            }
            this.publishTableVisible = false;
          });
          }
        },
        "请检查您所填写的信息是否有误"
      );
    },
    // 显示更新学习资源的对话框
    showUpdateNoticeDialog(row) {
      this.fileList = [];
      this.fileList2 = [];
      this.publishForm = row;
      if(row.poto){
        this.fileList.push({name:row.poto,url:row.poto})
      }
      if(row.title){
        this.fileList2.push({name:row.title,url:row.title})
      }
      // this.updateForm.content = row.content;
      // this.updateForm.nid = row.nid;
      // this.updateForm.status = row.status + "";
      // this.currentUpdateNoticeStatus = row.status + "";
      this.publishTableVisible = true;
      // window.setTimeout(() => {
      //   this.createUpdateWangEditor();
      // }, 200);
    },
    // 更新学习资源
    updateNotice() {
      utils.validFormAndInvoke(
        this.$refs["updateForm"],
        () => {
          notice.updateNotice(this.updateForm).then((resp) => {
            if (resp.code === 200) {
              this.getNoticeInfo();
              this.$notify({
                title: "Tips",
                message: resp.message,
                type: "success",
                duration: 2000,
              });
            } else {
              this.$notify({
                title: "Tips",
                message: resp.message,
                type: "error",
                duration: 2000,
              });
            }
            this.updateTableVisible = false;
          });
        },
        "请检查您所填写的信息是否有误"
      );
    },
  },
  computed: {
    //监测头部信息的token变化
    headers () {
      const signHeaders = {
        'body-string': '',
        'query-string': '',
        'x-nonce': `${utils.getRandomId()}`,
        'x-timestamp': `${new Date().getTime()}`
      }
      return {
        ...signHeaders,
        authorization: localStorage.getItem('authorization') || '',
        sign: generateSign(JSON.stringify(signHeaders)),
      }
    },
  }
};
</script>

<style scoped lang="scss">
@import "../../assets/css/admin/NoticeManage";
</style>
